import api from '@/plugins/api/index'

async function getAccessToken(callback) {
    try {
        const resp = await api.getViewerToken()
        console.log(resp)
        const { access_token, expires_in } = resp.data.data;
        callback(access_token, expires_in);
    } catch (err) {
        alert('Could not obtain access token. See the console for more details.');
        console.error(err);
    }
}

export async function initViewer(container) {
    const getViewerToken = await api.getViewerToken()
    return new Promise(function (resolve, reject) {
        console.log(getViewerToken)
        const resData = getViewerToken.data.data
        console.log(resData)
        Autodesk.Viewing.Initializer({ env: 'AutodeskProduction', getAccessToken }, function () {
            const config = {
                extensions: ['Autodesk.DocumentBrowser']
            };
            const viewer = new Autodesk.Viewing.GuiViewer3D(container, config);
            viewer.start();
            viewer.setTheme('light-theme');
            console.log(viewer)
            resolve(viewer);
        });
    });
}

export function loadModel(viewer, urn) {
    console.log(viewer)
    console.log(urn)
    return new Promise(function (resolve, reject) {
        function onDocumentLoadSuccess(doc) {
            const defaultGeometry = doc.getRoot().getDefaultGeometry();
            if (!defaultGeometry) {
                reject({
                    code: 'NO_DEFAULT_GEOMETRY',
                    message: '文档中没有默认几何体',
                    errors: ['该模型不包含默认几何体']
                });
                return;
            }

            // 加载文档节点
            viewer.loadDocumentNode(doc, defaultGeometry)
                .then(model => resolve(model))
                .catch(error => reject({
                    code: 'LOAD_FAILURE',
                    message: '加载文档节点失败',
                    errors: [error.message || error]
                }));
        }

        function onDocumentLoadFailure(code, message, errors) {
            reject({
                code: code || 'DOCUMENT_LOAD_FAILED',
                message: message || '文档加载失败',
                errors: errors || ['未知错误']
            });
        }

        viewer.setLightPreset(0);
        Autodesk.Viewing.Document.load('urn:' + urn, onDocumentLoadSuccess, onDocumentLoadFailure);
    });
}